<template>
  <div id="community-recommend" :class="{ 'dark-mode': isDarkMode }">
    <div class="recommend-content">
      <div class="columns-wrapper">
        <div class="column column-left">
          <div class="waterfall-item" v-for="(item, index) in leftColumnCards" :key="item.id || index"
            @click="handleCommunityCardClick(item, index * 2)">
            <div class="card-content">
              <div class="card-image" :style="{ height: calculateImageHeight(item) }">
                <img :src="item.data?.content?.data?.cover?.feed || ''" alt="" />
                <div class="choiceness-tag" v-if="isChoiceness(item)">精选</div>
                <van-icon v-if="item.data?.content?.type === 'video'" name="play" class="play-icon" />
                <van-icon v-if="isMultiPicture(item)" name="photo-o" class="layers-icon" />
              </div>
              <div class="card-description">{{ item.data?.content?.data?.description || '' }}</div>
              <div class="card-author">
                <img :src="item.data?.content?.data?.owner?.avatar || ''" alt=""
                  :class="['author-avatar', { 'round-avatar': isRoundAvatar(item) }]" />
                <div class="author-name">{{ item.data?.content?.data?.owner?.nickname || '未知用户' }}</div>
                <div class="collection-count">
                  <van-icon name="good-job-o" size="12" />
                  {{ formatCount(item.data?.content?.data?.consumption?.collectionCount || 0) }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="column column-right">
          <div class="waterfall-item" v-for="(item, index) in rightColumnCards" :key="item.id || index"
            @click="handleCommunityCardClick(item, index * 2 + 1)">
            <div class="card-content">
              <div class="card-image" :style="{ height: calculateImageHeight(item) }">
                <img :src="item.data?.content?.data?.cover?.feed || ''" alt="" />
                <div class="choiceness-tag" v-if="isChoiceness(item)">精选</div>
                <van-icon v-if="item.data?.content?.type === 'video'" name="play" class="play-icon" />
                <van-icon v-if="isMultiPicture(item)" name="photo-o" class="layers-icon" />
              </div>
              <div class="card-description">{{ item.data?.content?.data?.description || '' }}</div>
              <div class="card-author">
                <img :src="item.data?.content?.data?.owner?.avatar || ''" alt=""
                  :class="['author-avatar', { 'round-avatar': isRoundAvatar(item) }]" />
                <div class="author-name">{{ item.data?.content?.data?.owner?.nickname || '未知用户' }}</div>
                <div class="collection-count">
                  <van-icon name="good-job-o" size="12" />
                  {{ formatCount(item.data?.content?.data?.consumption?.collectionCount || 0) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="isLoadingMore && recommendList.length > 0" class="loading-more">
        <van-loading type="spinner" color="#1989fa">加载中...</van-loading>
      </div>
      <div v-if="!hasMore && recommendList.length > 0" class="no-more">
        <p>没有更多了</p>
      </div>
    </div>

    <CommunityDetail v-model:visible="showDetailVisible" :item="currentDetailItem" :item-list="recommendList"
      :current-index="currentDetailIndex" :is-loading-more="isLoadingMore" :has-more="hasMore"
      @close="handleDetailClose" @item-change="handleDetailItemChange" @load-more="handleDetailLoadMore" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated, onBeforeUnmount, nextTick } from 'vue';
import { getCommunityRecommend, getByFullUrl } from '@/api/api';
import CommunityDetail from '@/components/CommunityDetail.vue';
import { showToast } from 'vant';
import { useDarkModeStore } from '@/stores/darkMode';

const darkModeStore = useDarkModeStore();
const isDarkMode = computed(() => darkModeStore.isDarkMode);

// 数据状态
const recommendList = ref<any[]>([]); // 推荐列表数据
const loading = ref(false); // 初始加载状态
const nextPageUrl = ref<string | null>(null); // 下一页URL
const isLoadingMore = ref(false); // 是否正在加载更多
const hasMore = ref(true); // 是否还有更多数据

// 详情弹窗状态
const showDetailVisible = ref(false); // 详情弹窗显示状态
const currentDetailItem = ref<any>(null); // 当前详情项数据
const currentDetailIndex = ref(0); // 当前详情项索引

// 滚动相关
let lastToastTime = 0; // 上次提示时间（用于防抖）
const TOAST_INTERVAL = 2000; // 提示间隔时间（ms）
let scrollContainer: HTMLElement | null = null; // 滚动容器DOM引用

// 格式化数字：将数字转换为带单位的字符串（如：10000 -> 1.0万）
const formatCount = (count: number): string => {
  if (!count) return '0';
  if (count >= 10000) return `${(count / 10000).toFixed(1)}万`;
  return count.toString();
};

// 获取左列卡片数据（索引为偶数的卡片）
const leftColumnCards = computed(() => {
  return recommendList.value.filter((_, index) => index % 2 === 0);
});

// 获取右列卡片数据（索引为奇数的卡片）
const rightColumnCards = computed(() => {
  return recommendList.value.filter((_, index) => index % 2 === 1);
});

// 提取社区卡片数据：只提取 type=communityColumnsCard 且 dataType=FollowCard 的数据
const extractCommunityColumnsCard = (item: any): any | null => {
  if (item.type === 'communityColumnsCard' && item.data?.dataType === 'FollowCard') {
    return item;
  }
  return null;
};

// 计算图片高度：根据图片宽高比计算显示高度，适配瀑布流布局
const calculateImageHeight = (item: any): string => {
  if (!item?.data?.content?.data) return 'auto';
  const width = item.data.content.data.width || 0; // 图片原始宽度
  const height = item.data.content.data.height || 0; // 图片原始高度

  if (width === 0 || height === 0) {
    return 'auto';
  }

  // 计算每张图片的最大宽度（考虑屏幕宽度、左右边距、中间间距）
  const screenWidth = window.innerWidth || document.documentElement.clientWidth; // 屏幕宽度
  const bothSideSpace = screenWidth * 0.05 * 2; // 左右边距总和（5% * 2）
  const middleSpace = screenWidth * 0.015; // 中间间距（1.5%）
  const maxImageWidth = (screenWidth - bothSideSpace - middleSpace) / 2; // 每列图片最大宽度

  // 根据原始宽高比计算显示高度
  const imageHeight = (maxImageWidth * height) / width;
  return `${imageHeight}px`;
};

// 判断是否为精选内容：library === 'DAILY' 表示精选
const isChoiceness = (item: any): boolean => {
  return item.data?.content?.data?.library === 'DAILY';
};

// 判断是否为多图：检查 urls 数组长度是否大于1
const isMultiPicture = (item: any): boolean => {
  const urls = item.data?.content?.data?.urls;
  return urls && Array.isArray(urls) && urls.length > 1;
};

// 判断头像是否为圆形：iconType === 'round' 表示圆形头像
const isRoundAvatar = (item: any): boolean => {
  return item.data?.header?.iconType === 'round';
};

// 处理社区卡片点击：打开详情弹窗并设置当前项
const handleCommunityCardClick = (item: any, index: number) => {
  currentDetailItem.value = item;
  currentDetailIndex.value = index;
  showDetailVisible.value = true;
};

// 处理详情弹窗关闭：重置状态
const handleDetailClose = () => {
  showDetailVisible.value = false;
  currentDetailItem.value = null;
  currentDetailIndex.value = 0;
};

// 处理详情页滑动切换：更新当前显示的卡片索引和数据
const handleDetailItemChange = (index: number) => {
  currentDetailIndex.value = index;
  if (recommendList.value && recommendList.value[index]) {
    currentDetailItem.value = recommendList.value[index];
  }
};

// 处理详情页滑动到底部触发加载更多：加载完成后自动切换到新数据
const handleDetailLoadMore = async () => {
  if (isLoadingMore.value || !hasMore.value) {
    return;
  }
  await loadMore();
  // 加载完成后，如果有新数据，自动切换到第一个新加载的 item
  if (recommendList.value.length > currentDetailIndex.value + 1) {
    const nextIndex = currentDetailIndex.value + 1;
    handleDetailItemChange(nextIndex);
  }
};

// 获取推荐内容：从API获取初始数据并处理
const fetchRecommendData = async () => {
  loading.value = true;
  try {
    const data: any = await getCommunityRecommend();
    recommendList.value = [];

    if (data.itemList && data.itemList.length > 0) {
      data.itemList.forEach((item: any) => {
        const card = extractCommunityColumnsCard(item);
        if (card) {
          // 为每个卡片添加唯一 id（用于 key）
          if (!card.id) {
            card.id = card.data?.content?.data?.id || `card-${Date.now()}-${Math.random()}`;
          }
          recommendList.value.push(card);
        }
      });
    }
    nextPageUrl.value = data.nextPageUrl || null;
    hasMore.value = Boolean(nextPageUrl.value);
  } catch (err) {
    console.error('获取推荐内容失败:', err);
  } finally {
    loading.value = false;
  }
};

// 规范化下一页URL：将完整URL转换为相对路径
const normalizeNextUrl = (url: string): string => {
  if (!url) return '';
  try {
    const u = new URL(url);
    return u.pathname + u.search; // 返回路径和查询参数
  } catch {
    return url;
  }
};

// 加载更多数据：滚动到底部时触发
const loadMore = async () => {
  if (isLoadingMore.value || !hasMore.value || !nextPageUrl.value) return;
  isLoadingMore.value = true;
  try {
    // 处理URL：如果是完整URL则规范化，否则直接使用
    let url = nextPageUrl.value;
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = normalizeNextUrl(nextPageUrl.value);
      url = url.startsWith('/') ? url : `/${url}`;
    }
    const data: any = await getByFullUrl(url);
    if (data?.itemList?.length) {
      data.itemList.forEach((item: any) => {
        const card = extractCommunityColumnsCard(item);
        if (card) {
          // 为每个卡片添加唯一 id
          if (!card.id) {
            card.id = card.data?.content?.data?.id || `card-${Date.now()}-${Math.random()}`;
          }
          recommendList.value.push(card);
        }
      });
    }
    nextPageUrl.value = data.nextPageUrl || null;
    hasMore.value = Boolean(nextPageUrl.value);
  } catch (e) {
    console.error('推荐页加载更多失败:', e);
  } finally {
    isLoadingMore.value = false;
  }
};

// 处理滚动事件：监听滚动到底部，触发加载更多或显示提示
const handleScroll = () => {
  // 查找滚动容器（如果缓存不存在则重新查找）
  if (!scrollContainer) {
    scrollContainer = document.querySelector('.router-view-container > div') as HTMLElement;
  }
  if (!scrollContainer) return;

  const scrollTop = scrollContainer.scrollTop; // 当前滚动位置
  const viewH = scrollContainer.clientHeight; // 可视区域高度
  const docH = scrollContainer.scrollHeight; // 文档总高度

  // 当滚动到距离底部 120px 时触发
  if (scrollTop + viewH >= docH - 120) {
    if (!hasMore.value || !nextPageUrl.value) {
      // 没有更多数据，显示提示（防抖处理）
      const now = Date.now();
      if (now - lastToastTime > TOAST_INTERVAL) {
        showToast('已经到底了哦~');
        lastToastTime = now;
      }
      return;
    }
    loadMore();
  }
};

// 绑定滚动事件：在DOM更新后绑定滚动监听器
const bindScrollEvent = () => {
  // 先移除之前的监听器（如果存在）
  if (scrollContainer) {
    scrollContainer.removeEventListener('scroll', handleScroll as any);
    scrollContainer = null;
  }

  // 等待 DOM 更新后再绑定滚动事件
  nextTick(() => {
    setTimeout(() => {
      scrollContainer = document.querySelector('.router-view-container > div') as HTMLElement;
      if (scrollContainer) {
        scrollContainer.addEventListener('scroll', handleScroll, { passive: true });
      }
    }, 100);
  });
};

// 组件挂载时：获取数据并绑定滚动事件
onMounted(() => {
  fetchRecommendData();
  bindScrollEvent();
});

// 组件激活时：重新绑定滚动事件（keep-alive 缓存的组件重新激活时）
onActivated(() => {
  bindScrollEvent();
});

// 组件卸载前：清理滚动事件监听器
onBeforeUnmount(() => {
  if (scrollContainer) {
    scrollContainer.removeEventListener('scroll', handleScroll as any);
    scrollContainer = null;
  }
});
</script>

<style scoped lang="less">
#community-recommend {
  width: 100%;
  min-height: 88vh;
  padding-bottom: 2vh;
}

.recommend-content {
  padding: 2vh 4vw;
  box-sizing: border-box;
}

.columns-wrapper {
  display: flex;
  gap: 2vw;
  align-items: flex-start;
}

.column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2vh;
}

.waterfall-item {
  cursor: pointer;
  transition: transform 0.2s;

  &:active {
    transform: scale(0.98);
  }

  .card-content {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .card-image {
      position: relative;
      width: 100%;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
      }

      .choiceness-tag {
        position: absolute;
        top: 8px;
        left: 8px;
        background: rgba(25, 137, 250, 0.9);
        color: #fff;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 10px;
        font-weight: 500;
      }

      .play-icon {
        position: absolute;
        top: 5%;
        right: 2%;
        color: #fff;
        font-size: 10px;
        border-radius: 50%;
        border: 1px solid #fff;
        padding: 2px;
        opacity: 0.9;
      }

      .layers-icon {
        position: absolute;
        top: 5%;
        right: 2%;
        color: #fff;
        border-radius: 50%;
      }
    }

    .card-description {
      padding: 1.5vh 4vw;
      font-size: 13px;
      color: #333;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
      word-break: break-word;
    }

    .card-author {
      display: flex;
      align-items: center;
      gap: 2vw;
      padding: 1vh 4vw 1.5vh;
      box-sizing: border-box;

      .author-avatar {
        width: 32px;
        height: 32px;
        border-radius: 4px;
        object-fit: cover;
        flex-shrink: 0;

        &.round-avatar {
          border-radius: 50%;
        }
      }

      .author-name {
        flex: 1;
        font-size: 12px;
        color: #333;
        font-weight: 500;
      }

      .collection-count {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 11px;
        color: #999;
      }
    }
  }
}

// 夜间模式样式
#community-recommend.dark-mode {
  .waterfall-item {
    .card-content {
      background: #2a2a2a;
      box-shadow: 0 1px 3px rgba(255, 255, 255, 0.1);

      .card-description {
        color: #fff;
      }

      .card-author {
        .author-name {
          color: #fff;
        }

        .collection-count {
          color: #ccc;
        }
      }
    }
  }

  .no-more {
    color: #999;
  }
}

.loading-more {
  width: 100%;
  padding: 20px 0;
  text-align: center;
  clear: both;
}

.no-more {
  width: 100%;
  padding: 20px 0;
  text-align: center;
  color: #999;
  font-size: 12px;
  clear: both;
}
</style>
